package com.lyj.springcloud.controller;

import com.lyj.springcloud.entities.CommonResult;
import com.lyj.springcloud.entities.Payment;
import com.lyj.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Autowired
    PaymentService service;

    @Value("${server.port}")
    private String port;


    /*
        eureka 服务发现与注册
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 测试网关
     * @param id
     * @return
     */
    @GetMapping("/get")
    public String get(String id) {
        return port + "  get  ========>端口接入成功";
    }

    /**
     * 测试网关
     * @param id
     * @return
     */
    @GetMapping("/lb")
    public String lb(String id) {
        return port + "  lb ========>端口接入成功";
    }

    /**
     * 测试Ribbon 负载均衡
     * @param id
     * @return
     */
    @GetMapping("/getpaymentbyid")
    public CommonResult<Payment> getPayment(String id) {
        System.out.println(port +"========>端口接入成功");
        return service.getPayment(id);
    }

    /**
     * 测试 DiscoveryClient 服务发现功能
     * @return
     */
    @GetMapping("/discoveryClient")
    public Object discoveryClient() {
        List<String> services = discoveryClient.getServices();
        services.forEach(s -> {
            log.info("服务名称：" + s);
        });
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(obj ->{
            log.info(obj.getInstanceId()   + "====" + obj.getHost() + "====" + obj.getPort());
        });
        return discoveryClient;
    }

    /**
     * 测试负载均衡
     * @return
     */
    @GetMapping("/mylb")
    public CommonResult<String> myLb() {
        return new CommonResult<>("200",null,port);
    }

    /**
     *feign 调用测试接口
     */
    @GetMapping("/linkFeign")
    public CommonResult linkFeign() {
        return service.linkFeign();
    }


}
